﻿using NCP.Recruiting.ApplicationServices.Interfaces;
using NCP.Recruiting.ApplicationServices.Messaging.Candidates;
using NCP.Recruiting.Domain.Aggregates.Receipts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NCP.Infrastructure.Common;
using NCP.Recruiting.Domain.Aggregates.Candidates;
using NCP.Recruiting.ApplicationServices.Shared;

namespace NCP.Recruiting.ApplicationServices.Implementations
{
    public class ReceiptAppService : IReceiptAppService
    {
        private readonly IReceiptRepository _receiptRepository;
        private readonly ICandidateRepository _candidateRepository;
        public ReceiptAppService(IReceiptRepository receiptRepository, 
            ICandidateRepository candidateRepository)
        {
            _receiptRepository = receiptRepository;
            this._candidateRepository = candidateRepository;
        }

        public ResumeReplyResponse ResumeReply(ResumeReplyRequest request)
        {
            try
            {
                var receipt = new Receipt
                {
                    CompanyId = request.CompanyId,
                    DateCreated = DateTime.Now,
                    Deleted = false,
                    Jobseekers = request.Jobseekers,
                    LastUpdated = DateTime.Now,
                    Message = request.Message,
                    RepliedOn = DateTime.Now,
                    Subject = request.Subject,
                };
                receipt.GenerateNewIdentity();

                _receiptRepository.Add(receipt);

                _candidateRepository.UpdateItem(request.Id, (item) =>
                {
                    item.Status = (int)CandidateQueryStatus.Replied;
                });
                
                _receiptRepository.UnitOfWork.Commit();

                return new ResumeReplyResponse
                {
                    IsSuccess = true
                };
            }
            catch (Exception ex)
            {
                return new ResumeReplyResponse
                {
                    Exception = ex,
                    IsSuccess = false
                };
            }
        }
    }
}
